package cn.itsource.user.controller;

import cn.itsource.basic.exception.BusinessException;
import cn.itsource.user.service.IUserAddressService;
import cn.itsource.user.domain.UserAddress;
import cn.itsource.user.query.UserAddressQuery;
import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.basic.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 后端接口类；
 */
@RestController
@RequestMapping("/userAddress")
public class UserAddressController {

    @Autowired
    public IUserAddressService userAddressService;

    /**
     * 接口：添加或修改
     *
     * @param userAddress 传递的实体
     * @return AjaxResult 响应给前端
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody UserAddress userAddress) {
        if (userAddress.getId() != null) {
            userAddressService.update(userAddress);
        } else {
            userAddressService.add(userAddress);
        }
        return new AjaxResult();
    }

    /**
     * 接口：删除
     *
     * @param id
     * @return AjaxResult 响应给前端
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult del(@PathVariable("id") Long id) {
        userAddressService.delete(id);
        return new AjaxResult();
    }

    /**
     * 接口：批量删除
     *
     * @param ids
     * @return AjaxResult 响应给前端
     */
    @PatchMapping
    public AjaxResult patchDel(@RequestBody Long[] ids) {
        userAddressService.patchdel(ids);
        return new AjaxResult();
    }

    /**
     * 接口：查询单个对象
     *
     * @param id
     */
    @GetMapping("/{id}")
    public UserAddress findOne(@PathVariable("id") Long id) {
        return userAddressService.findOne(id);
    }


    /**
     * 接口：查询所有
     *
     * @return
     */
    @GetMapping
    public List<UserAddress> findAll() {
        return userAddressService.findAll();
    }


    /**
     * 接口：分页查询或高级查询
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping
    public PageResult<UserAddress> queryPage(@RequestBody UserAddressQuery query) {
        return userAddressService.queryPage(query);
    }

    @PutMapping("/saveUserAddress")
    public AjaxResult saveOrUpdateUserAddress(@RequestBody UserAddress userAddress, HttpServletRequest request){
        try {
            if (userAddress.getId() != null) {
                return userAddressService.updateUserAddress(userAddress,request);
            } else {
                return userAddressService.saveUserAddress(userAddress,request);
            }
        }catch (BusinessException b){
            b.printStackTrace();
            return new AjaxResult(false, b.getMessage()); //自己throw的异常
        }catch (Exception e) {
         e.printStackTrace();
         return new AjaxResult(false,"服务器内部错误【500】");
        }
    }
}
